package com.example.threebuttonapp;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.media.AudioManager;
import androidx.core.content.ContextCompat;
import android.content.Context;
import android.util.Log;

public class VibrationService extends Service {
    private static final String CHANNEL_ID = "VibrationServiceChannel";

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        startForeground(1, getNotification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(() -> {
            while (true) {
                // 这里可以添加条件判断是否需要震动
                // 例如：检查某个状态或接收某个信号
                if (MainActivity.isVibrating) { // 使用 MainActivity 中的震动计数变量来判断是否需要震动
                    Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                    if (vibrator != null) {
                        vibrator.vibrate(VibrationEffect.createOneShot(MainActivity.vibrationDuration, 255)); // 普通震动，震动时长为500毫秒
                    }
                    if(MainActivity.isSoundEnabled && MainActivity.vibrationCount >= 1){
                        MainActivity.alarmPlayer.start();
                        increaseVolume(15);
                    }
                    try {
                        Thread.sleep(MainActivity.vibrationDuration+9000); // 每100毫秒检查一次
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 恢复中断状态
                        break; // 退出循环
                    }
                }

                
            }
        }).start();
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Notification getNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        return new Notification.Builder(this, CHANNEL_ID)
                .setContentTitle("震动服务正在运行")
                .setContentText("检测打呼噜中...")
                .setSmallIcon(android.R.drawable.ic_dialog_info) // 使用默认图标
                .setContentIntent(pendingIntent)
                .build();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "震动服务通道",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    // 增加手机音量的方法，接受一个参数表示增加的音量级别
    private void increaseVolume(int increment) {
        AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            
            // 增加音量，确保不超过最大音量
            int newVolume = Math.min(currentVolume + increment, maxVolume);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, AudioManager.FLAG_SHOW_UI); // 增加音量并显示音量条
            // Log.d(TAG, "Volume increased to: " + newVolume);
        }
    }
} 